﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace Kojarskiy.Core
{
    public static class FileHelper
    {
        public static Bitmap CropBitmap(Bitmap bitmap)
        {
                int CropSize = Math.Min(bitmap.Width, bitmap.Height);
                Rectangle rect = new Rectangle(0, 0, CropSize, CropSize);
                Bitmap cropped = bitmap.Clone(rect, bitmap.PixelFormat);
                return cropped;
        }
        public static string CreateThumbnail(string filePath, string catalog)
        {
            int lnWidth = 200;
            int lnHeight = 200;
            var path = HttpContext.Current.Server.MapPath(filePath);
            var fileName = Path.GetFileName(filePath);
            var serverDirectory = HttpContext.Current.Server.MapPath("~/upload/" + catalog + "/thumbnails/");
            if (!Directory.Exists(serverDirectory)) Directory.CreateDirectory(serverDirectory);

            var thumbPath = Path.Combine(serverDirectory, fileName);

            Bitmap bmpOut = null;
            try
            {
                var loBMP = new Bitmap(path);
                float muliplier = 1;
                if (loBMP.Height > loBMP.Width)
                {
                    muliplier = (float)loBMP.Height / (float)loBMP.Width;
                    lnWidth = (int)(200 / muliplier);
                }
                else
                {
                    muliplier = (float)loBMP.Width / (float)loBMP.Height;
                    lnHeight = (int)(200 / muliplier);                    
                }

                bmpOut = new Bitmap(lnWidth, lnHeight);
                Graphics g = Graphics.FromImage(bmpOut);
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.FillRectangle(Brushes.White, 0, 0, lnWidth, lnHeight);
                g.DrawImage(loBMP, 0, 0, lnWidth, lnHeight);
                loBMP.Dispose();
                var oldFile = new FileInfo(thumbPath);
                if (oldFile.Exists) oldFile.Delete();

                bmpOut.Save(thumbPath, ImageFormat.Jpeg);
                return "~/upload/" + catalog + "/thumbnails/" + fileName;
            }
            catch
            {
                return "";
            }
        }
        public static string UploadPhoto(HttpPostedFileBase file, string catalog, int id, out string thumbPath, bool addWaterMark)
        {
            try
            {
                if (file != null && file.ContentLength > 0)
                {
                    // extract only the fielname
                    var fileName = Path.GetFileName(file.FileName);
                    var extention = Path.GetExtension(fileName);
                    string newName = id.ToString() + extention;

                    var relativePath = Path.Combine("~/upload/" + catalog + "/", newName);
                    var serverDirectory = HttpContext.Current.Server.MapPath("~/upload/" + catalog + "/");
                    if (!Directory.Exists(serverDirectory)) Directory.CreateDirectory(serverDirectory);
                    var path = Path.Combine(serverDirectory, newName);

                    if (addWaterMark)
                    {
                        CreateWaterMark(file, path);
                    }
                    else
                    {
                        var oldFile = new FileInfo(path);
                        if (oldFile.Exists) oldFile.Delete();
                        file.SaveAs(path);
                    }
                    thumbPath = CreateThumbnail(relativePath, catalog);

                    return relativePath;
                }
                if (HttpContext.Current.Request.Form["hPhoto"] != null)
                {
                    thumbPath = "";
                    return HttpContext.Current.Request.Form["hPhoto"];
                }
            }
            catch (Exception ex)
            {
                KojarskiyApplication.Log(KojarskiyApplication.ErrorType.Fatal, ex.Message, ex.StackTrace);
            }
            thumbPath = "";
            return "";
        }

        public static string UploadFile(HttpPostedFileBase file, string catalog, int id)
        {
            try
            {
                if (file != null && file.ContentLength > 0)
                {
                    // extract only the fielname
                    var fileName = Path.GetFileName(file.FileName);
                    var extention = Path.GetExtension(fileName);
                    string newName = id + extention;

                    var relativePath = Path.Combine("~/upload/" + catalog + "/", newName);
                    var serverDirectory = HttpContext.Current.Server.MapPath("~/upload/" + catalog + "/");
                    if (!Directory.Exists(serverDirectory)) Directory.CreateDirectory(serverDirectory);
                    var path = Path.Combine(serverDirectory, newName);

                    var oldFile = new FileInfo(path);
                    if (oldFile.Exists) oldFile.Delete();
                    file.SaveAs(path);

                    return relativePath;
                }
            }
            catch (Exception ex)
            {
                KojarskiyApplication.Log(KojarskiyApplication.ErrorType.Fatal, ex.Message, ex.StackTrace);
            }
            return "";
        }

        private static void CreateWaterMark(HttpPostedFileBase postedImage, string path)
        {
            var imgPhoto = Image.FromStream(postedImage.InputStream, true, true);
            int phWidth = imgPhoto.Width;
            int phHeight = imgPhoto.Height;

            var grPhoto = Graphics.FromImage(imgPhoto);

            Image imgWatermark = new Bitmap(HttpContext.Current.Server.MapPath("~/Content/Images/logo_wm.png"));
            int wmWidth = imgWatermark.Width;
            int wmHeight = imgWatermark.Height;
            var bmWatermark = new Bitmap(imgWatermark);

            var multiplier = imgPhoto.Width / imgWatermark.Width;

            bmWatermark.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

            int x = (phWidth - wmWidth / 2 * multiplier) / 2;
            int y = (phHeight - wmHeight / 2 * multiplier) / 2;

            using (grPhoto)
            {
                grPhoto.DrawImage(bmWatermark, x, y, wmWidth / 2 * multiplier, wmHeight / 2 * multiplier);
            }

            switch (Path.GetExtension(path))
            {
                case ".bmp":
                    imgPhoto.Save(path, ImageFormat.Bmp);
                    break;
                case ".gif":
                    imgPhoto.Save(path, ImageFormat.Gif);
                    break;
                case ".png":
                    imgPhoto.Save(path, ImageFormat.Png);
                    break;
                default:
                    imgPhoto.Save(path, ImageFormat.Jpeg);
                    break;
            }           
            imgPhoto.Dispose();
            imgWatermark.Dispose();
        }
        public static void DeleteFile(string path)
        {
            try
            {
                var oldFile = new FileInfo(HttpContext.Current.Server.MapPath(path));
                if (oldFile.Exists) oldFile.Delete(); 
            }
            catch (Exception ex)
            {
                KojarskiyApplication.Log(KojarskiyApplication.ErrorType.Fatal, ex.Message, ex.StackTrace);
            }
        }
        public static string UploadPrice(HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0)
            {
                // extract only the fielname
                var fileName = Path.GetFileName(file.FileName);
                var extention = Path.GetExtension(fileName);
                string newName = "price" + extention;
                // store the file inside ~/App_Data/uploads folder
                var relativePath = Path.Combine("~/upload/temp/", newName);
                var path = Path.Combine(HttpContext.Current.Server.MapPath("~/upload/temp/"), newName);
                file.SaveAs(path);
                return File.ReadAllText(path, Encoding.GetEncoding(1251));;
            }
            else
            {
                throw new NoNullAllowedException("File is empty!");
            }
        }

        public static string ToAbsoluteUrl(this string relativeUrl)
        {
            if (string.IsNullOrEmpty(relativeUrl))
                return relativeUrl;

            if (HttpContext.Current == null)
                return relativeUrl;

            if (relativeUrl.StartsWith("/"))
                relativeUrl = relativeUrl.Insert(0, "~");
            if (!relativeUrl.StartsWith("~/"))
                relativeUrl = relativeUrl.Insert(0, "~/");

            var url = HttpContext.Current.Request.Url;
            var port = url.Port != 80 ? (":" + url.Port) : String.Empty;

            return String.Format("{0}://{1}{2}{3}",
                url.Scheme, url.Host, port, VirtualPathUtility.ToAbsolute(relativeUrl));
        }
    }
}